package com.sh.util;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

/**
 * 	JAVA-JWT工具类
 */
@Component
public class JwtUtil {

    /**
     * logger
     */
    private static final Logger log = LoggerFactory.getLogger(JwtUtil.class);
    

    
    /**
     * 校验 token是否正确
     *
     * @param token  密钥
     * @param secret   私钥
     * @return 是否正确
     */
    public static boolean verify(String token, String username, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username",username)
                    .build();
            verifier.verify(token);
            log.info("token is valid");
            return true;
        } catch (Exception e) {
            log.info("token is invalid{}", e.getMessage());
            return false;
        }
    }

    /**
     * 从 获取用户信息
     *
     * @return token中包含的用户名
     */
    public static String getUsername(String token ) {
    	try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成 token
     *
     * @param secret   私钥
     * @return token
     */
    public static String sign(String username, String secret,long expireTime) {
        try {
        	//过期时间 
        	Date date = 
        			new Date(System.currentTimeMillis()+expireTime);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            String token = JWT.create() 
				            .withClaim("username", username)
				            .withExpiresAt(date)
				            .sign(algorithm);
            return token;
        } catch (Exception e) {
            log.error("error：{}", e);
            return null;
        }
    }
}
